//
//  WBNetWorkingManager.swift
//  WSWeibo
//
//  Created by guojianfeng on 2017/7/19.
//  Copyright © 2017年 guojianfeng. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
}

class WBNetWorkingManager: AFHTTPSessionManager {
    static let shared = WBNetWorkingManager()
    
    var accessToken: String? = "2.00v9sb7GRee_HC24a58b28c0yKQRJE"
    
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters:[String: AnyObject]?,completion:@escaping (_ json: AnyObject?, _ isSuccess: Bool)->()){
        guard let token = accessToken else {
            //FIXME: 发送过期通知
            completion(nil, false)
            return
        }
        
        var param = parameters
        if param == nil {
            param = [String: AnyObject]()
        }
        param!["access_token"] = token as AnyObject
        request(method: method, URLString: URLString, parameters: param, completion: completion)
    }
    
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters:[String: AnyObject]?,completion:@escaping (_ json: AnyObject?, _ isSuccess: Bool)->()){
        
        let success = {(task: URLSessionDataTask,json: Any?) -> () in
        completion(json as AnyObject,true)
        }
        
        let failure = {(task: URLSessionDataTask?,error: Error) -> () in
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token过期")
                //FIXME: 发送过期通知
            }
        completion(nil,false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
